package com.example.rabc.service.impl;

import com.example.rabc.service.ExternalAuthService;
import com.example.rabc.service.RealOAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Set;

/**
 * OAuth认证适配器 - 适配器模式的具体实现
 */
@Service
public class OAuthAuthAdapter implements ExternalAuthService {

    private static final Logger logger = LoggerFactory.getLogger(OAuthAuthAdapter.class);

    @Autowired
    private RealOAuthService realOAuthService;

    /**
     * OAuth用户认证
     * @param username 用户名
     * @param token OAuth2认证令牌
     * @return 是否认证成功
     */
    @Override
    public boolean authenticate(String username, String token) {
        logger.info("Using OAuth authentication for user: {}", username);

        try {
            // 获取当前认证信息
            Object authentication = SecurityContextHolder.getContext().getAuthentication();

            if (!(authentication instanceof OAuth2AuthenticationToken)) {
                logger.warn("Current authentication is not OAuth2");
                return false;
            }

            OAuth2AuthenticationToken oauth2Token = (OAuth2AuthenticationToken) authentication;
            OAuth2User oauth2User = oauth2Token.getPrincipal();

            // 验证用户名是否匹配
            return oauth2User != null && oauth2User.getName().equals(username);
        } catch (Exception e) {
            logger.error("Error during OAuth2 authentication", e);
            return false;
        }
    }

    /**
     * 从OAuth获取用户角色
     * @param username 用户名
     * @return 用户角色集合
     */
    @Override
    public Set<String> getUserRoles(String username) {
        logger.info("Getting roles from OAuth for user: {}", username);

        try {
            // 获取当前认证信息
            Object authentication = SecurityContextHolder.getContext().getAuthentication();

            if (!(authentication instanceof OAuth2AuthenticationToken)) {
                logger.warn("Current authentication is not OAuth2");
                return Collections.emptySet();
            }

            OAuth2AuthenticationToken oauth2Token = (OAuth2AuthenticationToken) authentication;
            OAuth2User oauth2User = oauth2Token.getPrincipal();

            if (oauth2User == null) {
                return Collections.emptySet();
            }

            // 获取用户角色
            return realOAuthService.getUserRoles(oauth2User);
        } catch (Exception e) {
            logger.error("Error getting roles from OAuth for user: {}", username, e);
            return Collections.emptySet();
        }
    }

    /**
     * 从OAuth获取角色权限
     * @param roleCode 角色代码
     * @return 角色权限集合
     */
    @Override
    public Set<String> getRolePermissions(String roleCode) {
        logger.info("Getting permissions from OAuth for role: {}", roleCode);

        // 在真实的实现中，这里会通过OAuth2提供商获取角色权限
        // 示例中我们返回默认权限
        switch (roleCode) {
            case "ROLE_USER":
                return Set.of("PERMISSION_READ", "PERMISSION_WRITE");
            case "ROLE_ADMIN":
                return Set.of("PERMISSION_READ", "PERMISSION_WRITE", "PERMISSION_ADMIN");
            default:
                return Collections.emptySet();
        }
    }
}